package io.renren.common.aspect;

import io.renren.common.annotation.NoRepeatSubmit;
import io.renren.common.exception.RRException;
import io.renren.common.utils.HttpContextUtils;
import io.renren.modules.app.utils.JwtUtils;
import org.apache.catalina.util.RequestUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 重复提交切面
 * steakliu
 */
@Component
@Aspect
public class NoRepeatSubmitAspect {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Pointcut("@annotation(repeatSubmit)")
    public void pointcutNoRepeat(NoRepeatSubmit repeatSubmit){ }

    @Around("pointcutNoRepeat(noRepeatSubmit)")
    public Object doNoRepeat(ProceedingJoinPoint point,NoRepeatSubmit noRepeatSubmit) throws Throwable {
        int i = noRepeatSubmit.lockTime();
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String token = request.getHeader("token");
        String url = request.getRequestURL().toString();
        String sign = url+"/"+token;
        Boolean key = redisTemplate.hasKey(sign);
        if (key){
            throw new RRException("请勿重复提交");
        }
        redisTemplate.opsForValue().set(sign,sign,i, TimeUnit.SECONDS);
        return point.proceed();
    }
}
